package com.apestech.framework.sql.table;

import com.apestech.framework.db.SqlSession;
import com.apestech.framework.dictionary.modul.Table;
import com.apestech.framework.json.JSONArray;
import com.apestech.framework.json.JSONObject;
import com.apestech.framework.sql.SqlUtil;
import com.apestech.framework.sql.lib.TableSql;
import com.apestech.framework.xml.table.modul.MasterTable;
import com.apestech.framework.xml.table.modul.Tables;
import java.util.ArrayList;

/**
 * @author hup
 * @create 2019-01-18-15:56
 */
public class MasterTableDelete extends SqlUtil {
    private SqlSession session;
    private Tables table;
    private MasterTable.SubTable subtable;
    private String ptabname;
    private String tabname;
    private JSONObject input;
    private JSONObject keymap;
    private String masterKey;
    private JSONObject relatDetail;

    public MasterTableDelete(SqlSession session, TableSql ddlsql, JSONObject input) throws Exception {
        this.session=session;
        this.input=input;
        table=ddlsql.getTable();
        subtable=table.getMaster().getTable();
        tabname=table.getTabName(table.getMasterTable());
        if(tabname==null) tabname=((Tables.TableRelat)table.getRelat().get(table.getRelat().getFirstKey())).getName();
        getKeyMap();
    }

    public MasterTableDelete(SqlSession session, String ptabname, Tables table, String tabname, MasterTable.SubTable subtable, String masterKey) throws Exception {
        this.session=session;
        this.table=table;
        this.ptabname=ptabname;
        this.tabname=tabname;
        this.subtable=subtable;
        this.masterKey=masterKey;
        keymap=new JSONObject();
        relatDetail=new JSONObject();
    }

    private void saveEmap(String masterTab, JSONObject emap, JSONObject masterData) throws Exception {
        ArrayList<String> tlist= (ArrayList<String>) relatDetail.get(masterTab);
        int tlen=tlist.size();
        for(int t=0; t<tlen; t++){
            String stab=tlist.get(t);
            JSONObject m= (JSONObject) keymap.get(stab);
            String fk=m.getString("fk");
            String self=m.getString("self");
            JSONObject k=new JSONObject();
            JSONObject mk=null;
            if(masterTab.equals(tabname)) mk=new JSONObject();
            if(fk.indexOf(",")<0){
                if(masterData!=null){
                    Object v=masterData.get(fk);
                    //k.put(self+"."+fk, v);
                    k.put(fk, v);
                    mk.put(fk, v);
                }
                else {
                    JSONObject tmap= (JSONObject) emap.get(masterTab);
                    ArrayList<String> tkeylist=tmap.getKeylist();
                    int tklen=tkeylist.size();
                    for(int tk=0; tk<tklen; tk++){
                        String key=tkeylist.get(tk);
                        k.put(self+"."+key, tmap.get(key));
                    }
                }
            }
            else {
                String[] fklist=fk.split(",");
                String[] selflist=self.split(",");
                int flen=fklist.length;
                for(int f=0; f<flen; f++){
                    if(!"".equals(fklist[f])){
                        if(masterData!=null){
                            Object v=masterData.get(fklist[f]);
                            //k.put(selflist[f]+"."+fklist[f], v);
                            k.put(fklist[f], v);
                            mk.put(fklist[f], v);
                        }
                        else {
                            JSONObject tmap= (JSONObject) emap.get(masterTab);
                            ArrayList<String> tkeylist=tmap.getKeylist();
                            int tklen=tkeylist.size();
                            for(int tk=0; tk<tklen; tk++){
                                String key=tkeylist.get(tk);
                                //k.put(self+"."+key, tmap.get(key));
                                k.put(key, tmap.get(key));
                            }
                        }
                    }
                }
            }
            if(masterData!=null) emap.put(tabname, mk);
            emap.put(stab, k);
            if(relatDetail.get(stab)!=null){
                saveEmap(stab, emap, null);
            }
        }
    }

    public void delete() throws Exception {
        JSONArray qlist=getMasterData();
        int qlen=qlist.size();
        String stab=tabname;
        JSONObject emap=new JSONObject();
        if(qlen>0){
            saveEmap(stab, emap, qlist.get(0));
        }
        for(int q=0; q<qlen; q++){
            JSONObject m=qlist.get(q);
            ArrayList<String> klist=table.getRelat().getOrderKeylist();
            int len=klist.size();
            for(int i=len-1; i>=0; i--){
                String tabname=table.getTable(klist.get(i)).getTabName();
                if(tabname==null) tabname=((Tables.TableRelat)table.getRelat().get(klist.get(i))).getName();
                JSONObject map=getDeleteMap(tabname, emap, m.get(masterKey));
                if(map!=null){
                    session.getForUpdate().deleteTable(tabname, map);
                }
            }
        }
    }

    private JSONObject getDeleteMap(String tabname, JSONObject emap, Object value){
        JSONObject map=new JSONObject((JSONObject) emap.get(tabname));
        ArrayList<String> klist=map.getKeylist();
        int len=klist.size();
        if(len==0) return null;
        for(int i=0; i<len; i++){
            String k=klist.get(i);
            map.put(k, value);
        }
        map.put("table_key","");
        map.put("autoCompletion","1");
        return map;
    }

    private JSONArray getMasterData() throws Exception {
        JSONArray qlist;
        Object kvalue=input.get(masterKey);  //|| (kvalue instanceof List)
        if(kvalue==null ) qlist=session.getForJSON().table(tabname, input);
        else {
            qlist=new JSONArray();
            JSONObject m=new JSONObject();
            m.put(masterKey, kvalue);
            qlist.add(m);
        }
        return qlist;
    }

    private void getKeyMap() throws Exception {
        keymap=new JSONObject();
        relatDetail=new JSONObject();
        masterKey=null;
        getkey();
    }

    protected void getkey() throws Exception {
        Table dtab=session.getDictTable(tabname);
        if(dtab==null) throw new Exception("当前表名["+tabname+"]不合法，请检查配置代码！");
        if(ptabname==null){
            masterKey=dtab.getPkKey().getPkColumn();
            if(masterKey.indexOf(",")>=0) throw new Exception("当前表["+tabname+"]对应主键必须为一个字段！");
        }
        if(ptabname!=null){
            String dcol=dtab.getPkFKey().getFieldByTable(ptabname).getColumnName();
            String fcol=dtab.getPkFKey().getFieldByTable(ptabname).getPkColumnName();
            String dkey="";
            String mkey="";
            if(dcol.indexOf(",")<0){
                mkey=dcol;
                dkey=fcol;
            } else {
                String[] dlist=dcol.split(",");
                String[] flist=fcol.split(",");
                int len=dlist.length;
                for(int i=0; i<len; i++){
                    if(!"".equals(dlist[i])){
                        if((","+masterKey+",").indexOf(","+flist[i]+",")>=0){
                            if(!"".equals(mkey)) mkey=mkey+",";
                            if(!"".equals(dkey)) dkey=dkey+",";
                            mkey=mkey+dlist[i];
                            dkey=dkey+flist[i];
                        }
                    }
                }
            }
            masterKey=mkey;
            JSONObject m=new JSONObject();
            m.put("fk", dkey);
            m.put("self", mkey);
            keymap.put(tabname, m);
            ArrayList<String> list;
            if(relatDetail.get(ptabname)==null) list=new ArrayList<String>();
            else list= (ArrayList<String>) relatDetail.get(ptabname);
            list.add(tabname);
            relatDetail.put(ptabname, list);
        }
        if(subtable.getSubTable()!=null){
            ArrayList<String> klist=subtable.getSubTable().getOrderKeylist();
            int klen=klist.size();
            for(int k=0; k<klen; k++){
                String tabid=klist.get(k);
                String tname=table.getTabName(tabid);
                if(tname==null) tname=((MasterTable.SubTable) subtable.getSubTable().get(tabid)).getName();
                MasterTableDelete query=new MasterTableDelete(session, tabname, table, tname,
                        subtable.getSubTable(tabid), masterKey);
                query.getkey();
                keymap.putAll(query.getKeymap());
                JSONObject dmap=query.getRelatDetail();
                if(relatDetail.get(dmap.getFirstKey())!=null){
                    ArrayList<String> s= (ArrayList<String>) relatDetail.get(dmap.getFirstKey());
                    ArrayList<String> d= (ArrayList<String>) dmap.get(dmap.getFirstKey());
                    s.addAll(d);
                    relatDetail.put(dmap.getFirstKey(), s);
                } else relatDetail.putAll(dmap);
            }
        }
    }

    protected JSONObject getKeymap() {
        return keymap;
    }

    protected JSONObject getRelatDetail() {
        return relatDetail;
    }
}
